package com.tencent.txcc.exception;

import com.tencent.txcc.enums.GlobleExceptionCode;
import com.tencent.txcc.result.JSONResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice
@Slf4j
public class GlobleExceptionHandler {

    @ExceptionHandler(Exception.class)
    public JSONResult GlobleExcertionHandler(Exception e){
        if (e.getClass().getSimpleName().indexOf("AccessDeniedException") != -1){
            return JSONResult.error(GlobleExceptionCode.USER_NO_PERMISSION_ERROR);
        }
        e.printStackTrace();
        // 1.打印日志
        log.error("发生全局异常，异常信息：{}", e.getMessage());
        return JSONResult.error(GlobleExceptionCode.ERROR);
    }

    @ExceptionHandler(BusinessException.class)
    public JSONResult businessExceptionHandler(BusinessException e){
        e.printStackTrace();
        // 1.打印日志
        log.error("发生业务异常，异常码：{}, 异常信息：{}", e.getMessage());
        return JSONResult.error(e);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JSONResult MethodArgumentNotValidException(MethodArgumentNotValidException e){

        BindingResult bindingResult = e.getBindingResult();
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        StringBuffer sb = new StringBuffer();
        allErrors.forEach(obj->{
            sb.append("--").append(obj.getDefaultMessage()).append("--");
        });
        return JSONResult.error(sb.toString(), "999");
    }
}
